<?php

namespace app\service;

use app\exception\ErrnoPlus;
use app\model\AppInfoTableModel;
use share\exception\ApiException;
use share\service\BaseModelService;
use share\service\ContextService;
use share\service\IpLocation;
use share\utils\Helper;

class AppInfoTableService extends BaseModelService
{
    public static function getModel()
    {
        return new AppInfoTableModel;
    }

    public static function getPrivacy($param){
        $appInfo = self::getByFilter(['package' => $param['package']]);
        if(empty($appInfo)){
            return null;
        }
        return $appInfo;
    }

    public static function getDownloadUrlByVendor($vendor,$ip){       
        $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $simpleVendor = self::getSimpleVendor($vendor);
        if(!empty($simpleVendor)){
            $vendor = $simpleVendor;
        }        
        $appInfo = self::getAllByFilter(["vendor" => $vendor]);
        if(empty($appInfo)){
            return null;
        }  
        $appType = Helper::getClientTypeByUserAgent($userAgent);        
        $urlKey = 'download_ios';
        if($appType === Helper::CLIENT_TYPE_OF_ANDROID){      
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE) || $ip !== "0.0.0.0") {
                $info = IpLocation::info($ip);
                if(empty($info)){
                    return null;
                }
                $urlKey  = 'download_tencet'; // 国内去应用宝
                if(isset($info['country']) && isset($info['country']['isoCode']) && $info['country']['isoCode'] !== 'CN'){
                    $urlKey  = 'download_google';// 国内去google
                }
            }
        }
        foreach ($appInfo as $item) {         
            if (!empty($item[$urlKey])) {
                return trim($item[$urlKey]);
            }
        }
        return null;
    }


    public static function getSimpleVendor($vendor){
        $map = [
            'HDT-NEUTRALEN' => 'ENZ',
            'HDT-NEUTRAL' => 'ENZ',
            'HDT-LENOVOEN' => 'HDT-LENOVO',
            'TUNGSON-CK' => 'HDT-CK',
            'TUNGSON-FSLINK' => 'FSLINK',
            'TUNGSON-ZHIREN' => 'FSLINK',
            'ENZ-ZHIREN' => 'ZHIREN',
        ];
        return  isset($map[$vendor]) ? $map[$vendor] :'';
    }

    public static function getListVendorInfo($filter){
        if(empty($filter)){
            $filter = [];
        }
        $data = AppInfoTableModel::field('vendor,vendor_name')->group('vendor,vendor_name')->select();
        return Helper::listArrayColumn($data,['vendor'=>'vendor','vendor_name' => 'name']);
    }

    public static function addPackage($packageInfo){
        $filter = [
            'package' => $packageInfo['package'],
        ];
        $exist = self::getByFilter($filter);
        if(!empty($exist)){
            throw new ApiException("package [".$packageInfo['package']."] is already exist",ErrnoPlus::COMMON_ERROR);
        }
        $item = Helper::arrayCamelKeyToUnderscore($packageInfo);
        $item['is_android'] = $item['android'] == 0 ? 0 : 1;
        $item['is_ios'] = $item['ios'] == 0 ? 0 : 1;
        unset($item['android']);
        unset($item['ios']);
        return self::add($item);
    }

    public static function updatePackage($packageInfo){
        $id = $packageInfo['id'];
        unset($packageInfo['id']);
        $origin = self::getBase($id);
        if(empty($origin)){
            throw new ApiException("app is not exist",ErrnoPlus::COMMON_ERROR);
        }
        $item = Helper::arrayCamelKeyToUnderscore($packageInfo);
        if(isset($item['android'])){
            $item['is_android'] = $item['android'] == 0 ? 0 : 1;
            unset($item['android']);
        }
        if(isset($item['ios'])){
            $item['is_ios'] = $item['ios'] == 0 ? 0 : 1;        
            unset($item['ios']);
        }
        // 要修改的包名已存在
        if(isset($item['package']) && $item['package'] !== $origin['package']){
            $filter = [
                'package' => $item['package'],
            ];
            $exist = self::getByFilter($filter);
            if(!empty($exist)){
                throw new ApiException("package [".$packageInfo['package']."] is already exist",ErrnoPlus::COMMON_ERROR);
            }
        }
        $update = [];
        foreach($item as $key => $val){
            if($val != $origin[$key]){
                $update[$key] = $val;
            }
        }
        // 有需要更新的信息
        if(count($update) > 0){
            self::update($id,$update);
        }
    }

    /**
     * 删除App包
     */
    public static function delPackage($id){
        // 删除商户的关联关系
        AppMchTableService::delByFilter(['aid' => $id]);
        return self::del($id);
    }

    public static function buildCondition($param)
    {
        $filter = [];
        if(isset($param['vendor'])){
            $filter['vendor'] = $param['vendor'];
        }
        if(isset($param['package'])){
            $filter['package'] = $param['package'];
        }
        return $filter;
    }

}
